package com.secneo.appshare.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.adapter.FeedsButtonAdapter;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.Feed;
import com.secneo.appshare.api.RemoteApi.Feeds;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.threads.FeedsThread;
import com.secneo.mp.api.database.DatabaseHelper;

public class OtherZoneFansActivity extends CommonMenuActivity
{
	
	private int mPageNumber;
	private int mFocusPosition;
	private boolean mReadyToGetFeeds = false;
	private ProgressDialog mDynDisPMProgressBar = null;
	private Feeds mLocalFeeds = new Feeds();
	
	private LinearLayout mOtherZoneFansLayout;
	private TextView mOtherFansTxt;
	private GridView mOtherFansGridView;
	private Button mBtnAttentAllFans;

	private Button mRetIv;
	private TextView topbarTxt;
	
	private LinearLayout progress_layout;
	private View errorView;
	
	private FeedsThread zoneFansThread = null;
	
	private FeedsButtonAdapter feedAdapter = null;

	private String mUserId;
	private String mUserName;
	private String mAvatarName;
	
	Drawable dw =null;
    public int radioChecked=-1; 
    

	private Handler mAttentMultipleHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch(msg.what) 
			{
			case Constants.MSG_ATTENT_MULTIPLE_FINISH:
				try{
					feedAdapter.setFeedList(mLocalFeeds.feeds);
					feedAdapter.notifyDataSetChanged();
				
				} catch(Exception ex) {
					ex.printStackTrace();
				}
				break;

			case Constants.MSG_ATTENT_SINGLE_FINISH:
				try{
					String finishedUid = feedAdapter.getFinishedUid();

					int size = mLocalFeeds.feeds.size();
					for(int i=0; i<size; i++)
					{
						Feed feed = mLocalFeeds.feeds.get(i);
						if(feed.uid.equals(finishedUid))
						{
							mLocalFeeds.feeds.get(i).is_attent = 1;
							break;
						}
					}

					feedAdapter.setFeedList(mLocalFeeds.feeds);
					feedAdapter.notifyDataSetChanged();
					
				} catch(Exception ex) {
					ex.printStackTrace();
				}
				break;
			}
			
			super.handleMessage(msg);
		}
	};
    
    public Handler mHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case Constants.MSG_GET_FEEDS_NETWORK_ERROR:
					mReadyToGetFeeds = true;
					if(mDynDisPMProgressBar != null && mDynDisPMProgressBar.isShowing()){
						mDynDisPMProgressBar.dismiss() ;
					}
					showNetworkErrView(Constants.MSG_GET_FEEDS_NETWORK_ERROR) ;
					break;
					
				case Constants.MSG_GET_FANS_FINISH:
					mReadyToGetFeeds = true;
					if(mDynDisPMProgressBar != null && mDynDisPMProgressBar.isShowing()){
						mDynDisPMProgressBar.dismiss() ;
					}
					
					updateFeeds(zoneFansThread.getFeeds());
					
					progress_layout.setVisibility(View.GONE);
					refreshOtherFansGridView(mLocalFeeds);
					break;
					
				case Constants.MSG_GET_FEEDICON_FINISH:
					mOtherFansGridView.invalidateViews();
					break;
					
				default:
					break ;
			}
			super.handleMessage(msg);
		}

	};
	
	private void clearFeeds(){
		mPageNumber = 1;
		mFocusPosition = 0;
		
		if(null!=mLocalFeeds.feeds){
			mLocalFeeds.feeds.clear();
		}
	}


	private void updateFeeds(Feeds feeds){
		++mPageNumber;
		if(null==mLocalFeeds.feeds){
			mLocalFeeds.feeds = new ArrayList<Feed>();
		}
		mLocalFeeds.feeds.addAll(feeds.feeds);
		mLocalFeeds.fb_invite_popup = feeds.fb_invite_popup;
		mLocalFeeds.msgs = feeds.msgs;
		mLocalFeeds.total = feeds.total;
		mLocalFeeds.fansTotal = feeds.fansTotal;
		mLocalFeeds.attentTotal = feeds.attentTotal;
	}
	

	private void showNetworkErrView(int action){
		errorView.setVisibility(View.VISIBLE);
		progress_layout.setVisibility(View.GONE);
	}
	
	public void refreshOtherFansGridView(final Feeds feeds) 
	{
		feedAdapter = new FeedsButtonAdapter(this, mAttentMultipleHandler, feeds.feeds);
		mOtherZoneFansLayout.setVisibility(View.VISIBLE);

		int fansCount = feeds.total;
		String otherFansTitle = OtherZoneFansActivity.this.getResources().getString(R.string.title_other_fans,
				fansCount);
		mOtherFansTxt.setText(otherFansTitle);
		
		mOtherFansGridView.setNumColumns(4);
		mOtherFansGridView.setAdapter(feedAdapter);
		mOtherFansGridView.setSelection(mFocusPosition);
		mOtherFansGridView.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView parent, View v, int position, long id)
			{
				try 
				{
					Feed userInfo = feeds.feeds.get(position);
					String uid = LocalStore.getLocaleStoreInstance().getUid();
					if(uid.equals(userInfo.uid)){
						Intent intent=new Intent();
						intent.setClass(OtherZoneFansActivity.this, UserAppActivity.class);
						OtherZoneFansActivity.this.startActivity(intent);
					}
					else{
						Intent intent = new Intent(); 
						intent.setClass(OtherZoneFansActivity.this, AppsOtherUserActivity.class);

						Bundle mBundle = new Bundle();
						mBundle.putString("uid", uid);
						mBundle.putString("other_uid", userInfo.uid);
						mBundle.putString("user_icon", userInfo.user_icon);
						mBundle.putString("user_name", userInfo.user_name);
						intent.putExtras(mBundle);
						startActivity(intent);
					}
					
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});
	}
	

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appshare_other_zone_fans);
		AppShareApplication.getInstance().addActivity(this);
		
		mPageNumber = 1;

		mOtherZoneFansLayout = (LinearLayout) findViewById(R.id.zone_fans_layout);
		mOtherFansTxt = (TextView) findViewById(R.id.other_fans_txt);
		mOtherFansGridView = (GridView) findViewById(R.id.gridview_fans_feeds);
		mOtherFansGridView.setOnScrollListener(mGridViewScrollListner);
		mBtnAttentAllFans = (Button) findViewById(R.id.btnAttentAllFans);

		mBtnAttentAllFans.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				DatabaseHelper dh=new DatabaseHelper(OtherZoneFansActivity.this);
				dh.insertUserAppPopularityBycatagory(OtherZoneFansActivity.this,2040);
				dh.close();
				
				startAttentThread();
			}
		});
		
		progress_layout = (LinearLayout) findViewById(R.id.progress_layout);
		errorView = OtherZoneFansActivity.this.findViewById(R.id.error_user);
		
		mRetIv = (Button)findViewById(R.id.img_ret);
		mRetIv.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		}) ;
		

		Bundle bundle = getIntent().getExtras();
		mUserId = "";
		if(bundle.containsKey("userid")){
			mUserId = bundle.getString("userid");
		}
		mUserName = "";
		if(bundle.containsKey("username")){
			mUserName = bundle.getString("username");
		}
		mAvatarName = "";
		if(bundle.containsKey("avatarname")){
			mAvatarName = bundle.getString("avatarname");
		}
		topbarTxt = (TextView) findViewById(R.id.topbar_txt);
		topbarTxt.setText(mUserName + getString(R.string.word_defollower));
		
	}

	
	// 获得ta的关注列表
	private void startGetOtherFans()
	{
		progress_layout.setVisibility(View.VISIBLE);
		mOtherZoneFansLayout.setVisibility(View.GONE);
		
		zoneFansThread = new FeedsThread(this, mHandler, mPageNumber, mUserId, Constants.USER_TYPE_FOLLOWER, Constants.feedGetTypeAll);
		zoneFansThread.start();
	}
	

	private void startAttentThread()
	{
		Thread followMultipleThread = new Thread() 
		{
			public void run()
			{
				final String uid = LocalStore.getLocaleStoreInstance(OtherZoneFansActivity.this).getUid();
				final List<String> uidList = new ArrayList<String>();
				
				int size = mLocalFeeds.feeds.size();
				for(int i=0; i<size; i++)
				{
					Feed feed = mLocalFeeds.feeds.get(i);
					if(1 != feed.is_attent)
					{
						uidList.add(feed.uid);
					}
				}
				
				RemoteApiImpl remoteApi = new RemoteApiImpl();
				boolean ret = remoteApi.uploadFollowedFriends(OtherZoneFansActivity.this, uid, uidList);
				if(ret)
				{
					size = mLocalFeeds.feeds.size();
					int uidListSize=0;
					for(int i=0; i<size; i++)
					{
						uidListSize = uidList.size();
						Feed feed = mLocalFeeds.feeds.get(i);
						for(int j=0; j<uidListSize; j++)
						{
							if(feed.uid.equals(uidList.get(j)))
							{
								mLocalFeeds.feeds.get(i).is_attent = 1;
								uidList.remove(j);
								break;
							}
						}
					}
					Message msg = new Message();
					msg.what = Constants.MSG_ATTENT_MULTIPLE_FINISH;
					mAttentMultipleHandler.sendMessage(msg);
				}
			}
		};
		followMultipleThread.start();
	}
	

	@Override
	protected void onStart() 
	{
		startGetOtherFans();
		super.onRestart();
	}

	
	
	@Override
	protected void onDestroy() 
	{
		zoneFansThread.stopRun();
		
		if(feedAdapter != null)
		{
			feedAdapter.freeDrawable();
			feedAdapter=null;
		}
		
		clearFeeds();
		
		super.onDestroy();
	}
	

	private OnScrollListener mGridViewScrollListner = new OnScrollListener()
	{
		private int firstItem = 0;
		private int lastItem = 0;
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
		{
			firstItem = firstVisibleItem;
			lastItem = firstVisibleItem + visibleItemCount;
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState)
		{
			if (feedAdapter != null && lastItem == feedAdapter.getCount() && scrollState == OnScrollListener.SCROLL_STATE_IDLE)
			{
				Log.e("MyTag", "Total:"+mLocalFeeds.total);
				Log.e("MyTag", "return Size:"+mLocalFeeds.feeds.size());
				
				if(mLocalFeeds.total==mLocalFeeds.feeds.size()){
					return;
				}
				if (!mReadyToGetFeeds)
					return;
				mReadyToGetFeeds = false;

            	mDynDisPMProgressBar = ProgressDialog.show(
            			OtherZoneFansActivity.this, null, "加载中，请稍候..." ,true);
				
				mFocusPosition = firstItem;

				zoneFansThread = new FeedsThread(OtherZoneFansActivity.this, mHandler, mPageNumber, mUserId, 
						Constants.USER_TYPE_FOLLOWER, Constants.feedGetTypeAll);
						
				zoneFansThread.start();
				
			}
		}
	};
	
	
	
	
}
